package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import commonTypes.Dish;

public class DishesDaoImpl implements DishesDao{
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public Dish getDishById(int dishId) {
		String sqlStr = "SELECT * FROM dishes WHERE DishID = ?";
		final Dish dish = new Dish();
		jdbcTemplate.query(sqlStr,new Object[] {dishId}, new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				dish.setId(rs.getInt("DishID"));
				dish.setName(rs.getString("Name"));
				dish.setType(rs.getInt("Type"));
				dish.setPrice(rs.getFloat("Price"));
				dish.setImage(rs.getString("Image"));
				dish.setHasMeat(rs.getInt("Meat")==0?false:true);
				dish.setHasGlucose(rs.getInt("Glucose")==0?false:true);
				dish.setStackable(rs.getInt("Stackable")==0?false:true);
				dish.setCustomizable(rs.getInt("Customizable")==0?false:true);
				dish.setDescribe(rs.getString("Describe"));
			}
		});
		return dish;
	}

	public List<Dish> getAllDishes() {
		String sqlStr = "SELECT * FROM dishes";
		final List<Dish> dishes =new ArrayList<Dish>();
		jdbcTemplate.query(sqlStr, new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				while(!rs.isAfterLast()) {
					Dish dish = new Dish();
					dish.setId(rs.getInt("DishID"));
					dish.setName(rs.getString("Name"));
					dish.setType(rs.getInt("Type"));
					dish.setPrice(rs.getFloat("Price"));
					dish.setImage(rs.getString("Image"));
					dish.setHasMeat(rs.getInt("Meat")==0?false:true);
					dish.setHasGlucose(rs.getInt("Glucose")==0?false:true);
					dish.setStackable(rs.getInt("Stackable")==0?false:true);
					dish.setCustomizable(rs.getInt("Customizable")==0?false:true);
					dish.setDescribe(rs.getString("Describe"));
					dishes.add(dish);
					rs.next();
				}
			}
		});
		return dishes;
	}

}
